/** OTA详情轮询 */
let timer: any = null
const DEFAULT_DELAY = 2000

const loop = (resolve: Function, reject: Function, request: Function, needCloseMsg = false, delay = DEFAULT_DELAY) => {
  const detail = async () => {
    try {
      const { status, closeMsg, extraDataJson, verifyFlag } = await request()

      if (!needCloseMsg && status === 0 && closeMsg) {
        clearTimeout(timer)
        timer = null
        resolve({ closeMsg })
      } else if (verifyFlag === 1) {
        clearTimeout(timer)
        timer = null
        resolve({ verifyFlag })
      } else if (Object.keys(extraDataJson).length > 0) {
        clearTimeout(timer)
        timer = null
        resolve({ extraDataJson, loop: () => (timer = setTimeout(detail, delay)) })
      } else {
        timer = setTimeout(detail, delay)
      }
    } catch (error: any) {
      clearTimeout(timer)
      timer = null
      reject(error)
    }
  }

  detail()
}

const clear = () => {
  clearTimeout(timer)
  timer = null
}

export { loop, clear }
